package com.ws.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ws.bean.Images;
import com.ws.bean.vo.ImageVo;
import com.ws.service.ImageService;
import com.ws.utils.Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

@Controller
@RequestMapping("/image")
public class ImageController {
    @Autowired
    ImageService imageService;

    @RequestMapping("/list")
    public String list(Model model, ImageVo imageVo){
        PageHelper.startPage(imageVo.getCurrentPage(), imageVo.getPageSize());
        ArrayList<Images> list = imageService.list(imageVo);
        PageInfo pageInfo = new PageInfo(list);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("imageVo", imageVo);
        return "/image/list";
    }

    //添加图片
    @RequestMapping("/toAdd")
    public String toAdd(Integer route_id, Model model){
        model.addAttribute("route_id", route_id);
        return "image/add";
    }

    @RequestMapping("/add")
    public String add(Images images, MultipartFile[] image) throws IOException {
        for (int i = 0; i < image.length; i++) {
            if (image[i].getSize() > 0) {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                String houZhui = image[i].getOriginalFilename().split("\\.")[1];
                images.setImage_url(uuid + "." + houZhui);
                image[i].transferTo(new File(Res.fileDir + uuid + "." + houZhui));
                imageService.add(images);
            }
        }
        return "redirect:/image/list";
    }
    @RequestMapping("/delete")
    public String delete(Integer image_id){
        imageService.delete(image_id);
        return "redirect:/image/list";
    }


}